package com.xuantu.learn.core.thread;

import java.util.concurrent.Semaphore;

/**
 * 如何控制某个方法允许并发访问线程的个数
 * 
 * @author fengzp
 *
 */
public class SemaphoreTest {

	static Semaphore semaphore = new Semaphore(5, true);

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						test();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}).start();
		}
	}

	private static void test() throws InterruptedException {
		semaphore.acquire();
		System.out.println(Thread.currentThread().getName() + "进来了");
		Thread.sleep(1000);
		System.out.println(Thread.currentThread().getName()+"走了");
		semaphore.release();
	}

}
